package io.renren.modules.pms.service.impl;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import io.renren.common.exception.RRException;
import io.renren.modules.pms.entity.QiniuEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.xml.transform.Result;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class QiniuService {

    @Autowired
    private QiniuEntity qiniu;
    
    //获取认证对象
    public Auth getAuth() {
        return Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
    }
    
    private Configuration getConfiguration() {
        return new Configuration(getRegion(qiniu.getRegion()));
    }

    private Region getRegion(String region){
        switch(region){
            case "huabei":
                return Region.huabei();
            case "huanan":
                return Region.huanan();
            case "beimei":
                return Region.beimei();
            case "huadong":
            default:
                return Region.huadong();

        }

    }
    //获取上传凭证
    public String getUploadToken(String bucket) {
        if (StringUtils.isEmpty(bucket)) {
            bucket = qiniu.getBucket();
        }
        return getAuth().uploadToken(bucket);
    }

    //上传文件
    public String uploadFile(byte[] fileBytes, String fileName, String bucket) {
        try {
            String token = getUploadToken(bucket);
            UploadManager uploadManager = new UploadManager(getConfiguration());

            Response response = uploadManager.put(fileBytes, fileName, token);
            // 解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException ex) {
            throw new RRException("文件上传失败：" + ex.getMessage());
        }
    }

    //删除文件
     public boolean deleteFile(String fileName, String bucket) {
        try {
            if (StringUtils.isEmpty(bucket)) {
                bucket = qiniu.getBucket();
            }
            // 修正这行：完整的BucketManager构造函数
            BucketManager bucketManager = new BucketManager(getAuth(),getConfiguration());
            bucketManager.delete(bucket, fileName);
            return true;
        } catch (QiniuException ex) {
            throw new RRException("文件删除失败：" + ex.getMessage());
        }
    }
    //获取文件列表
    public FileListing listFiles(String prefix, String marker, String bucket) {
        try {
            if (StringUtils.isEmpty(bucket)) {
                bucket = qiniu.getBucket();
            }
            BucketManager bucketManager = new BucketManager(getAuth(), getConfiguration());
            return bucketManager.listFiles(bucket, prefix, marker, 1000, null);
        } catch (QiniuException ex) {
            throw new RRException("获取文件列表失败：" + ex.getMessage());
        }
    }

    //获取文件外链
    public String getFileUrl(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        String encodedFileName;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            encodedFileName = fileName;
        }
        return String.format("%s/%s", qiniu.getDomain(), encodedFileName);
    }
}